#include <bits/stdc++.h>
using namespace std;
 
struct edge{
	int  f, t, w;
}e[1002000];
int  n, m, et, ma, c, u[100020];
 
bool cmp(edge a,edge b){
	return a.w < b.w;
}
 
int getf(int x){
	if(u[x] == x) return x;
	else u[x]=getf(u[x]); 
	return u[x];
}
 
void mg(int x,int y){
	int xf = getf(x),yf = getf(y);
	if(xf != yf) {
		u[xf] = u[yf];
	}
	return;
}
 
int get_num() {
	int ans = 0;
	char tmp = getchar();
	while (tmp < '0' || tmp > '9') tmp = getchar();
	while (tmp <= '9' && tmp >= '0') {
		ans = ans * 10 + tmp - 48;
		tmp = getchar();
	}
	return ans;
}
 
int main() {
	freopen("in.txt", "r", stdin);
//	freopen("different.out", "w", stdout);
	int c = get_num();
	while(c--) {
		memset(e, 0, sizeof(e));
		n = get_num();
		m = get_num();
		for(int i = 1; i <= n; i++) u[i] = i;
		for(int i = 0; i < m; i++) {
			e[i].f = get_num();
			e[i].t = get_num();
			e[i].w = get_num();
		}
		sort(e, e + m, cmp);
		int ans = 0x7fffffff;
		for(int i = 0; i <= m - (n - 1); i++) {
			for(int j = 1; j <= n; j++) u[j] = j;
			int mi = e[i].w, mx = e[i].w;
			mg(e[i].f , e[i].t);
			int tmp = 0;
			for(int j = i; j < m; j++) {
				if(getf(e[j].f) == getf(e[j].t)) continue;
				tmp++;
				mx = e[j].w;
				mg(e[j].f, e[j].t);
				if(tmp == n - 1) break;
			}
			ans = min(mx - mi, ans);
		}
		printf("%d\n", ans);
	}
	return 0;
}
